use strict;
use File::Find;
use File::Basename;

use lib '/var/www/perl/galleri';

use Galleri;
my $g = new Galleri();
my $pjx = $g->pjx;

$pjx->register( jsShowImages => \&jsShowImages );
$pjx->register( jsSelectImage => \&jsSelectImage );
$pjx->register( jsDeSelectAll => \&jsDeSelectAll );
$pjx->register( jsSelectManyImages => \&jsSelectManyImages );
$pjx->register( jsSelectAllInDir => \&jsSelectAllInDir );
$pjx->register( jsAddSelectedToAlbums => \&jsAddSelectedToAlbums );

sub jsAddSelectedToAlbums {
  
  my @album_ids = @_;
  
  my $user = $g->active_user;
  
  my @si = sort { $a->image_id->filename cmp $b->image_id->filename }  Galleri::DB->resultset('SelectedImages')->search({username => $user->username, selected => 1 });
  
  for( @album_ids ){
    
    my $album = Galleri::DB->resultset("Albums")->find( $_ );
    
    my $n = scalar( $album->album_images ) + 1;
    
    for( @si ){
      
      my $ai = $album->album_images->find_or_create( { image_id => $_->image_id, image_order => $n++ } );
      
    }
    
  }
  
  "Done";
  
}

sub jsDeSelectAll {
  
  my $user = $g->active_user;
  Galleri::DB->resultset('SelectedImages')->search({username => $user->username })->delete;
  
  "Done";
  
}

sub jsSelectAllInDir {
  my($select_status, $orig_dir) = @_;
  
  return unless $orig_dir;
  my $dir = "/var/www/perl/galleri/image_repository/" . $orig_dir;
  return unless -d $dir;
  
  my @images;
  
  find
    (
     {
      wanted => sub {
	return unless -f $_;
	s|.*image_repository/?||;
	push @images, $_;
      },
      no_chdir => 1,
     },
     $dir
    );
  
  my $user = $g->active_user;
  
  for( @images ){
    
    next unless $_;
    my ($image) = Galleri::DB->resultset('Images')->search( { filename => $_ } );
    
    $image = Galleri::DB->resultset('Images')->create( { filename => $_, rotation => 0 } ) unless $image;
    
    next unless $image;
    
    my ($s) = $image->selected_images->find_or_create( { username => $user->username } );
    $s->selected( $select_status );
    
    $s->update;
    
  }
  
  "Done";
  
}

sub jsSelectManyImages {
  
  my($select_status, @images) = @_;
  
  my $user = $g->active_user;
  
  for my $image_id (@images) {
    
    my($image) = Galleri::DB->resultset('Images')->find( $image_id ) or next;
    
    my($s) = Galleri::DB->resultset('SelectedImages')->find_or_create
      ( { image_id => $image->id, username => $user->username } );
    
    $s->selected( $select_status );
    
    $s->update;
    
  }
  
  "Done";
}

sub jsSelectImage {
  
  my $image_id = shift or return;
  
  my($select_status) = @_;
  
  my($image) = Galleri::DB->resultset('Images')->find( $image_id );
  
  my $user = $g->active_user;
  
  my($s) = Galleri::DB->resultset('SelectedImages')->find_or_create
    ( { image_id => $image->id, username => $user->username } );
  
  if(defined $select_status){
    $s->selected( $select_status );
  }
  else{
    $s->selected( int !$s->selected );
  }
  
  $s->update;
  
  ($image_id, $s->selected);
  
}

sub jsShowImages {
  
  my($orig_dir,$offset,$skip_navpanel) = @_;
  
  return unless $orig_dir;
  
  my $page_size = 25;
  
  $offset ||= 0;
  
  my $dir = "/var/www/perl/galleri/image_repository/" . $orig_dir;
  
  return unless -d $dir;
  
  my @images;
  
  find
    (
     {
      wanted => sub {
	
	return unless -f $_;
	
	s|.*image_repository/?||;
	
	push @images, $_;
	
      },
      
      no_chdir => 1,
      
     },
     $dir
    );
  
  @images = sort @images;
  
  my $count = @images;
  
  @images = @images[$offset..($offset+$page_size-1)];
  
  my $html = "<table class=\"thumbs\"><tr>";
  
  my $user = $g->active_user;
  
  my $i;
  for( @images ){
    
    next unless $_;
    
    my ($image) = Galleri::DB->resultset('Images')->search( { filename => $_ } );
    
    $image = Galleri::DB->resultset('Images')->create( { filename => $_, rotation => 0 } ) unless $image;
    
    my ($s) = $image->selected_images->search( { username => $user->username } );
    my $selected = $s->selected if $s;
    
    $html .= sprintf qq{<td><input type="hidden" id="idinput%d" value="%d">
<img id="%d" onclick="jsSelectImage(['idinput%d'],[handle_click])" class="thumb%s" src="loader.pl?id=%d&size=%d"
   onmousedown="nudge1(this);return true;" onmouseup="nudge2(this);return true;">
<br/><small>%s</small></td>}, ($image->id)x4, ($selected?" selected":""), $image->id, 1, basename $image->filename;
    $html .= "</tr><tr>\n" unless ++$i % 5;
    
  }
  
  $html .= "</tr></table>";
  
  $html .= sprintf
    q{<form onsubmit="return false">
      <input type="hidden" id="dirname" value="%s">
      <input type="hidden" id="first" value="0">
      <input type="hidden" id="prev" value="%d">
      <input type="hidden" id="next" value="%d">
      <input type="hidden" id="last" value="%d">
      <input type="hidden" id="dummy" value="1">
      </form>}, $orig_dir, ($offset-$page_size), ($offset+$page_size), (($count-1)-($count-1)%$page_size) ;
  
  my $this_page = int $offset / $page_size + 1;
  my $max_page = int ( ($count-1) / $page_size + 1 ) ;
  
  return ( $html,
    ( $skip_navpanel ? "" : sprintf q{
	<img onmousedown="nudge1(this);return true;" onmouseup="nudge2(this);return true;"
	onclick = "jsShowImages(['dirname','first','dummy'],[handle_navigation])"
	 class="left" src="images/stock-goto-first.png" id="gofirst" style="visibility:hidden">
        
	<img onmousedown="nudge1(this);return true;" onmouseup="nudge2(this);return true;"
	onclick = "jsShowImages(['dirname','prev','dummy'],[handle_navigation])"
	 class="left" src="images/stock-go-back.png" id="goprev" style="visibility:hidden">
	
	<span id="navigation">Side <span id="thispage">%d</span>/<span id="maxpage">%d</span></span>
	
	<img onmousedown="nudge1(this);return true;" onmouseup="nudge2(this);return true;"
	onclick = "jsShowImages(['dirname','next','dummy'],[handle_navigation])"
	 class="right" src="images/stock-go-forward.png" id="gonext">
        
	<img onmousedown="nudge1(this);return true;" onmouseup="nudge2(this);return true;"
	onclick = "jsShowImages(['dirname','last','dummy'],[handle_navigation])"
	 class="right" src="images/stock-goto-last.png" id="golast">
     }, $this_page, $max_page ), 
     $this_page, $max_page
  );
  
}

$g->add_css
( q{

   /*                                                          */
   /* Styles for the tree.                                     */
   /*                                                          */
SPAN.TreeviewSpanArea A {
  font-size: 10pt; 
  font-family: verdana,helvetica; 
  text-decoration: none;
  color: black;
}
SPAN.TreeviewSpanArea A:hover {
  color: '#820082';
}

SPAN.TreeviewSpanArea {
  overflow-y: scroll;
  height: 580px;
  display: block;
}

#left {
  width: 420px;
  min-height: 580px;
  text-align: left;
}
#view {

}
#right {
  
  float: right;
  width: 240px;
}

#navpanel img {
  position: relative;
}

span.panel {
  text-decoration: underline;
  color: blue;
  cursor: pointer;
}

#panel {
  display: none;
  border: 1px solid #e0e0e0;
  padding: 10px; 
  margin: 5px;
  background-color: #fafafa;
}

#left img.thumb {
  border: 2px solid blue;
  height: 80px;
  width: 80px;
  position: relative;
}

#thumbs_here {
  text-align: left;
}

#left img.selected {
  border: 2px solid red;
}

#left table.thumbs {
  border-spacing: 2px;
  border-collapse: separate;
}

#left td {
  text-align: center;
  vertical-align: bottom;
}

#navpanel {
	text-align: center;
}

#navigation {
	vertical-align: top;
	display: inline;
}


});

$g->add_js
(q{

function addClass(element, className) {
  if (!hasClass(element, className)) {
    if (element.className) element.className += " " + className;
    else element.className = className;
  }
};
   
function removeClass(element, className) {
  var regexp = new RegExp("(^|\\\s)" + className + "(\\\s|$)");
  element.className = element.className.replace(regexp, "$2");
};
   
function hasClass(element, className) {
  var regexp = new RegExp("(^|\\\s)" + className + "(\\\s|$)");
  return regexp.test(element.className);
};

function handle_add_toalbum(){
  
  s = document.getElementById("selected_albums");
  if(!s)
    return;
  
  albums = Array();
  
  for( i=0; i<s.options.length; i++ ){
    
    o = s.options[i];
    if(o.selected)
      albums[ albums.length ] = o.id;
    
  }
  
  jsAddSelectedToAlbums( albums, [] );
  
}

function handle_select_allindir(status){
  
  if(status == 0)
    thediv = "zero";
  else
    thediv = "one";
  
  d = document.getElementById("thumbs_here");
  if(!d)
    return;
  
  imgs = d.getElementsByTagName("img");
  
  for( i=0; i<imgs.length; i++ ){
    img = imgs[i];
    if( status == 0 ){
      while( hasClass( img, "selected" ))
        removeClass( img, "selected" );
    }
    else {
      if(!hasClass( img, "selected" ))
        addClass( img, "selected" );
    }
  }
  
  jsSelectAllInDir( [thediv, "dirname"],[]);
  
}

function handle_select_allonpage(status){
  
  if(status == 0)
    thediv = "zero";
  else
    thediv = "one";
  
  d = document.getElementById("thumbs_here");
  if(!d)
    return;
  
  imgs = d.getElementsByTagName("img");
  
  ids = Array();
  ids[0] = thediv;
  
  for( i=0; i<imgs.length; i++ ){
    img = imgs[i];
    ids[i+1] = "idinput" + img.id;
    if( status == 0 ){
      while( hasClass( img, "selected" ))
        removeClass( img, "selected" );
    }
    else {
      if(!hasClass( img, "selected" ))
        addClass( img, "selected" );
    }
  }
  
  jsSelectManyImages(ids,[]);
  
}

function one() {
  return 1;
}

function handle_click(id,selected){
  
  img = document.getElementById(id);
  
  if(!img)
    return;
  
  if(selected == 0){
    removeClass( img, "selected" );
  }
  else if(selected){
    addClass( img, "selected" );
  }
}

function handle_deselect_all(){
  
  d = document.getElementById("thumbs_here");
  if(!d)
    return;
  
  imgs = d.getElementsByTagName("img");
  
  for( i=0; i<imgs.length; i++ ){
    img = imgs[i];
    while( hasClass( img, "selected" ) ) {
      removeClass( img, "selected" );
    }
  }
  
}

function toggle_panel(){
  f = document.getElementById("panel");
  if(!f)
    return;

  v = document.getElementById("view");
  if(!v)
    return;
  
  if(!f.style.display){
    f.style.display = "block";
    //v.style.display = "none";
  }
  else{
    f.style.display = "";
    //v.style.display = "block";
  }
  
  
}

function handle_navigation( html, navpanel, thispage, maxpage ){
  
  gofirst = document.getElementById("gofirst");
  gonext = document.getElementById("gonext");
  goprev = document.getElementById("goprev");
  golast = document.getElementById("golast");
  
  thispage = parseInt(thispage);
  maxpage = parseInt(maxpage);
  
  if( thispage <= 1 && maxpage <= 1 ){
    gofirst.style.visibility="hidden";
    goprev.style.visibility="hidden";
    gonext.style.visibility="hidden";
    golast.style.visibility="hidden";
  }
  else if(maxpage > 1 && thispage == 1){
    gofirst.style.visibility="hidden";
    goprev.style.visibility="hidden";
    gonext.style.visibility="visible";
    golast.style.visibility="visible";
  }
  else if(maxpage > 1 && thispage < maxpage){
    gonext.style.visibility="visible";
    golast.style.visibility="visible";
    goprev.style.visibility="visible";
    gofirst.style.visibility="visible";
  }
  else if( thispage >= maxpage ){
    goprev.style.visibility="visible";
    gofirst.style.visibility="visible";
    gonext.style.visibility="hidden";
    golast.style.visibility="hidden";
  }
  
  
  document.getElementById("thumbs_here").innerHTML = html;
  if(navpanel)
    document.getElementById("navpanel").innerHTML = navpanel;
  document.getElementById("thispage").innerHTML = thispage;
  document.getElementById("maxpage").innerHTML = maxpage;
  
}

function nudge1(img) {
  img.style.left = '1px';
  img.style.top = '1px';
}

function nudge2(img) {
  img.style.left = '0px';
  img.style.top = '0px';
}

function enlarge_view() {
  v = document.getElementById("view");
  t = document.getElementById("thumbs");
  t.style.display = "none";
  v.style.width = "100%";
}

function shrink_view() {
  v = document.getElementById("view");
  t = document.getElementById("thumbs");
  t.style.display = null;
  v.style.width = null;
  
}

});

$g->add_content
(
 subject => 'File Manager',
 body => 
 [sprintf q{
  <script src="Treeview/ua.js"></script>
  <script src="Treeview/ftiens4.js"></script>
  <script src="Treeview/fileManager.js"></script>
  <DIV style="visibility:hidden;position:absolute; top:0; left:0;"><TABLE border=0><TR><TD><FONT size=-2><A style="font-size:7pt;text-decoration:none;color:silver" href="http://www.treemenu.net/" target=_blank>Javascript Tree Menu</A></FONT></TD></TR></TABLE></DIV>

<div style="width: 680px;">
<div id="right">

<span class="panel" onclick="javascript:toggle_panel()" onfocus="if(this.blur)this.blur()">panel</span>


<span class="TreeviewSpanArea">
  <SCRIPT>initializeDocument()</SCRIPT>
  <NOSCRIPT>
   A tree for site navigation will open here if you enable JavaScript in your browser.
  </NOSCRIPT>
</span>



</div>

<div id="left">

<div id="panel">
<form onsubmit="return false">
<input id="one" value="1" type="hidden">
<input id="zero" value="0" type="hidden">
<span class="panel" onclick="handle_select_allonpage(1)">select all on page</span><br/>
<span class="panel" onclick="handle_select_allonpage(0)">deselect all on page</span><br/>
<span class="panel" onclick="handle_select_allindir(1)">select all in dir</span><br/>
<span class="panel" onclick="handle_select_allindir(0)">deselect all in dir</span><br/>
<span class="panel" onclick="jsDeSelectAll([],[handle_deselect_all])">deselect all images</span><br/>
Filter directories:<br/>
<input name="dirs"><br/>
<input type="checkbox" id="select_dirs"> only dirs with selected<br/>
Filter files:<br/>
<input name="files"><br/>
<input type="checkbox" id="select_files"> only selected files<br/>
Albums: <input id="album_filter" size="16" value=".*"><br/>
<select id="selected_albums" multiple size="4" style="width:100%">
%s
</select><br/>
<span class="panel" onclick="handle_add_toalbum()">add selected to album(s)</span><br/>


</form>
</div>


<div id="view">

<div id="thumbs_here">
</div>

<div id="navpanel">
</div>

</div>


</div>
</div>


}, join "\n", map { sprintf qq{<option id="%d" value="%d">%s</option>\n}, ($_->id)x2, $_->name } Galleri::DB->resultset("Albums")->search({ locked => 0}) ],
 
 
);

$g->output;

